package com.ruoyi.project.channel.businessInfo.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import com.ruoyi.project.channel.clickFormUser.domain.ClickFormUser;
import com.ruoyi.project.channel.smsInfo.service.ISmsInfoService;
import com.ruoyi.project.channel.userLevelConfig.domain.UserLevelConfig;
import com.ruoyi.project.channel.userLevelConfig.service.IUserLevelConfigService;
import com.ruoyi.project.channel.vwBusinessCashStat.domain.VwBusinessCashStat;
import com.ruoyi.project.channel.vwBusinessCashStat.service.IVwBusinessCashStatService;
import com.ruoyi.project.channel.vwIncomeDayStat.domain.VwIncomeDayStat;
import com.ruoyi.project.channel.vwIncomeDayStat.service.IVwIncomeDayStatService;
import com.ruoyi.project.pay.PayConfig;
import com.ruoyi.project.pay.PayServiceImpl;
import com.ruoyi.project.system.config.service.IConfigService;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 商家信息操作处理
 *
 * @author zero
 * @date 2019-05-04
 */
@Controller
@RequestMapping("/channel/businessInfo")
public class BusinessInfoController extends BaseController {
    private String prefix = "channel/businessInfo";
    @Autowired
    private PayServiceImpl payService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private ISmsInfoService smsInfoService;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private IConfigService configService;
    @Autowired
    private PasswordService passwordService;

    @RequiresPermissions("channel:businessInfo:view")
    @GetMapping()
    public String businessInfo() {
        return prefix + "/businessInfo";
    }

    /**
     * 查询商家列表
     */
    @RequiresPermissions("channel:businessInfo:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BusinessInfo businessInfo) {
        startPage();
        List<BusinessInfo> list = businessInfoService.selectBusinessInfoList(businessInfo);
        return getDataTable(list);
    }


    /**
     * 导出商家列表
     */
    @RequiresPermissions("channel:businessInfo:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BusinessInfo businessInfo) {
        List<BusinessInfo> list = businessInfoService.selectBusinessInfoList(businessInfo);
        ExcelUtil<BusinessInfo> util = new ExcelUtil<BusinessInfo>(BusinessInfo.class);
        return util.exportExcel(list, "businessInfo");
    }

    /**
     * 新增商家
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 修改商家
     */
    @GetMapping("/edit/{businessId}")
    public String edit(@PathVariable("businessId") Long businessId, ModelMap mmap) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(businessId);
        mmap.put("businessInfo", businessInfo);
        return prefix + "/edit";
    }

    @GetMapping("/{businessId}")
    @ResponseBody
    public AjaxResult getBusinessInfo(@PathVariable("businessId") Long businessId) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(businessId);
        return AjaxResult.success("success", businessInfo);
    }

    /**
     * 修改商家
     */
    @GetMapping("/info")
    public String info(ModelMap mmap) {
        User user = ShiroUtils.getSysUser();
        mmap.put("user", user);
        mmap.put("qrcode", payConfig.getHost().replace("/admin", "") + "/#/register/" + user.getRemark());
        return prefix + "/detail";
    }

    /**
     * 修改商家
     */
    @GetMapping("/host/json")
    @ResponseBody
    public AjaxResult getInfo() {
        String str = payConfig.getHost().replace("/admin", "") + "/#/register";
        HashMap map = new HashMap();
        map.put("host", str);
        return AjaxResult.success("success", map);
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("channel:businessInfo:edit")
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPayPwd")
    @ResponseBody
    public AjaxResult resetPayPwd(String id, String password) {
        User user1 = ShiroUtils.getSysUser();
//        boolean b = smsInfoService.validateCode(user1.getPhonenumber(),code.trim());
//        boolean b = smsInfoService.validateCode(user1.getEmail().trim(), code.trim());
//        if (!b) {
//            return AjaxResult.error("手机验证码出错！");
//        }
        return businessInfoService.resetPayPwd(id, password);
    }

    @GetMapping("/resetBusinessPayPwd")
    public String resetBusinessPayPwd(ModelMap mmap) {
        mmap.put("user", ShiroUtils.getSysUser());
        return "system/user/profile/resetPayPwd";
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetBusinessPayPwd")
    @ResponseBody
    public AjaxResult resetBusinessPayPwd(String oldPassword, String newPassword) {
        User user = getSysUser();
        if (StringUtils.isNotEmpty(newPassword) && businessInfoService.matches(oldPassword)) {
            return businessInfoService.resetPayPwd(user.getUserId() + "", newPassword);
        } else {
            return error("oldPassword error");
        }
    }

    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/address")
    @ResponseBody
    public AjaxResult resetAddress(@RequestBody Map<String, String> map) {
        String address = map.get("address");
        String addressPhone = map.get("addressPhone");
        String addressUserName = map.get("addressUserName");
        String addressCode = map.get("addressCode");
        User user = getSysUser();
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(user.getUserId());
        businessInfo.setRemark(address);
        businessInfo.setAddressCode(addressCode);
        businessInfo.setAddressPhone(addressPhone);
        businessInfo.setAddressUserName(addressUserName);
        businessInfoService.updateBusinessInfo(businessInfo);
        return AjaxResult.success("success");
    }

    /**
     * 修改保存商家
     */
    @RequiresPermissions("channel:businessInfo:edit")
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(BusinessInfo businessInfo) {
        return toAjax(businessInfoService.updateBusinessInfo(businessInfo));
    }


    /**
     * 删除商家
     */
    @RequiresPermissions("channel:businessInfo:remove")
    @Log(title = "商家", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(businessInfoService.deleteBusinessInfoByIds(ids));
    }

    @GetMapping("/checkPassword")
    @ResponseBody
    public boolean checkPassword(String password) {
        if (businessInfoService.matches(password)) {
            return true;
        }
        return false;
    }

    @GetMapping("/checkPassword1")
    @ResponseBody
    public boolean checkPassword1(String password) {
        String newPwd = passwordService.encryptPassword(ShiroUtils.getLoginName(), password, ShiroUtils.getSysUser().getSalt());
        if (ShiroUtils.getSysUser().getPassword().equals(newPwd)) {
            return true;
        }
        return false;
    }

    /**
     * 确认绑定
     */
    @Log(title = "我的信息", businessType = BusinessType.UPDATE)
    @GetMapping("/myInfo")
    @ResponseBody
    public AjaxResult getMyClickUserInfo() {
        User user = ShiroUtils.getSysUser();
        BusinessInfo clickFormUser = businessInfoService.selectBusinessInfoById(user.getUserId());
        if (user.getStatus().equals("1") || clickFormUser.getStatus().equals("1")) {
            return AjaxResult.error("用户已经注销不可用！");
        }
        clickFormUser.setSalt("");
        clickFormUser.setApiKey("");
        clickFormUser.setPayPwd("");
        return AjaxResult.success("success", clickFormUser);
    }

    /**
     * 获取用户资金信息
     */
    @Log(title = "我的信息", businessType = BusinessType.UPDATE)
    @GetMapping("/amountInfo")
    @ResponseBody
    public AjaxResult getMyClickUserAmountInfo() {
        return AjaxResult.success("success", businessInfoService.getMyClickUserAmountInfo());
    }

    /**
     * 下单
     */
    @Log(title = "下单充值", businessType = BusinessType.UPDATE)
    @PostMapping("/recharge")
    @ResponseBody
    public AjaxResult recharge(@RequestBody Map<String, String> recharge, ModelMap mmap) {
        User user = ShiroUtils.getSysUser();
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(user.getUserId());
        String amount = recharge.get("amount"); // 充值金额
        ChannelOrder channelOrder = new ChannelOrder();
        channelOrder.setBusinessId(user.getUserId());
        channelOrder.setAmount(BigDecimal.valueOf(Double.valueOf(amount)));
        channelOrder.setPayType(recharge.get("payType"));
        channelOrder.setFromAlipayAccount(businessInfo.getBankNo());
        AjaxResult result = payService.addOrder(channelOrder, null);
        if (result.get("data") == null) {
            AjaxResult.error(result.get("msg") + "");
        }

        HashMap r = (HashMap) result.get("data");
        String payUrl = businessInfo.getBankNo();
        if (payUrl == null) {
            payUrl = (String) r.get("payUrl");
        }
//        payUrl = (String) r.get("payUrl");

        return AjaxResult.success("success", payUrl);
    }

    @GetMapping("/getCustomers")
    @ResponseBody
    public AjaxResult getCustomers() {
        String helpCustomerNo = configService.selectConfigByKey("help_customer_no");
        String withdrawCustomerNo = configService.selectConfigByKey("withdraw_customer_no");
        String rechargeCustomerNo = configService.selectConfigByKey("recharge_customer_no");
        HashMap<String, String> map = new HashMap<>();
        map.put("helpCustomerNo", helpCustomerNo);
        map.put("withdrawCustomerNo", withdrawCustomerNo);
        map.put("rechargeCustomerNo", rechargeCustomerNo);
        return AjaxResult.success("success", map);
    }

    @PostMapping("/updateAddress")
    @ResponseBody
    public AjaxResult updateAddress(Long userId) {
        String address = businessInfoService.getAddress();
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(userId);
        businessInfo.setBankNo(address);
        businessInfoService.updateBusinessInfo(businessInfo);
        return AjaxResult.success("success");
    }
}
